﻿using UnityEngine;
using System.Collections.Generic;


namespace Framework.AssetsManager
{
    public class NetLoaderRunner : MonoBehaviour
    {

        protected static NetLoaderRunner instance = null;

        public static NetLoaderRunner Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = FindObjectOfType(typeof(NetLoaderRunner)) as NetLoaderRunner;
                    if (instance == null)
                    {
                        GameObject obj = new GameObject("NetLoaderRunner");
                        DontDestroyOnLoad(obj);
                        instance = obj.AddComponent<NetLoaderRunner>();
                        obj.hideFlags = HideFlags.HideAndDontSave;
                    }
                    if (instance == null)
                        Debug.LogError("Failed to create instance of " + typeof(NetLoaderRunner).FullName + ".");
                }
                return instance;
            }
        }

        private List<NetLoader> m_list = new List<NetLoader>();
        private List<NetLoader> m_delList = new List<NetLoader>();


        void Awake()
        {
            NetLoader.SetNetLoaderRunner(this);
        }

        void Update()
        {
            List<NetLoader>.Enumerator v = m_list.GetEnumerator();

            while (v.MoveNext())
            {
                if (v.Current.isDone)
                    m_delList.Add(v.Current);
                else
                    v.Current.Update();
            }

            List<NetLoader>.Enumerator d = m_delList.GetEnumerator();

            while (d.MoveNext())
            {
                m_list.Remove(d.Current);
            }
        }

        public void Add(NetLoader _loader)
        {
            m_list.Add(_loader);
        }

    }
}